package org.university.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.university.entity.TeachingClass;
import org.university.repository.TeachingClassRepository;
import org.university.service.TeachingClassService;

@Service
public class TeachingClassServiceImpl extends GenericServiceImpl<TeachingClass, Integer> implements TeachingClassService {

    private static final Logger logger = LoggerFactory.getLogger(TeachingClassServiceImpl.class);
    private final TeachingClassRepository teachingClassRepository;

    public TeachingClassServiceImpl(TeachingClassRepository repository, TeachingClassRepository teachingClassRepository) {
        super(repository);
        this.teachingClassRepository = teachingClassRepository;
    }

    @Override
    public TeachingClass save(TeachingClass teachingClass) {
        Integer id = teachingClass.getClassId();
        logger.info("保存教学班ID: {}", id);
        if (id != null && teachingClassRepository.existsById(id)) {
            throw new IllegalArgumentException("教学班ID已存在: " + id);
        }
        return teachingClassRepository.save(teachingClass);
    }

    @Override
    public Page<TeachingClass> findAll(Pageable pageable) {
        logger.info("查询所有教学班: 分页信息={}", pageable);
        return teachingClassRepository.findByDeletedFalse(pageable);
    }

    @Override
    public Page<TeachingClass> findAll() {
        logger.info("查询所有教学班（无分页）");
        return teachingClassRepository.findByDeletedFalse(Pageable.unpaged());
    }

    @Override
    public void deleteById(Integer id) {
        logger.info("删除教学班ID: {}", id);
        teachingClassRepository.findById(id).ifPresent(teachingClass -> {
            teachingClass.setDeleted(1);
            teachingClassRepository.save(teachingClass);
        });
    }
}